<template>
  <div>
    <el-button type="primary" icon="el-icon-edit" @click="dialogue = true">添加</el-button>
    <el-dialog title="添加公告" :visible.sync="dialogue" width="35%">
      <el-form :model="form" ref="form" :rules="rule" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" autocomplete="off" style="width: 70%" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input type="textarea" :rows="6" placeholder="请输入内容" autocomplete="off" style="width: 70%" v-model="form.content">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogue = false">取 消</el-button>
        <el-button type="primary" @click="addNotice">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { addNotice } from '@/api/system/notice'
import Cookies from 'js-cookie'

export default {
  name: 'AddButton',
  inject: ["getNoticeList"],
  data() {
    const validate = (rule, value, callback) => {
      if (value.length > 0) {
        callback()
      } else {
        callback(new Error('不能为空'))
      }
    }
    return {
      dialogue: false,
      form: {
        id: 0,
        userId: '',
        title: '',
        content: '',
        createTime: ''
      },
      rule: {
        title: [{ required: true, trigger: 'blur', validator: validate }],
        content: [{ required: true, trigger: 'blur', validator: validate }]
      }
    }
  },
  methods: {
    addNotice() {
      this.$refs.form.validate(valid => {
        if(valid) {
          let data = {
            "content": this.form.content,
            "title": this.form.title,
            "userId": JSON.parse(Cookies.get("user")).id
          }
          addNotice(data).then(res => {
            if(res.data.code === 200) {
              this.$message.success({
                message: res.data.message,
                duration: 1000
              })
              this.dialogue = false
              this.clear()
            } else {
              // this.$message.error({
              //   message: res.data.message,
              //   duration: 1000
              // })
            }
            this.getNoticeList()
          })
        } else {
          return false
        }
      })
    },
    clear() {
      this.form =  {
        id: 0,
        userId: '',
        title: '',
        content: '',
        createTime: ''
      }
    }
  }
}
</script>

<style scoped>

</style>
